package com.guyu.common.validator.constraintvalidators;


import com.guyu.common.validator.constraints.DateLimit;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.Setter;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 校验输入的时间是否在偏移范围内
 */
@Setter
public class DateLimitValidatorImpl implements ConstraintValidator<DateLimit, Date> {

    private int min;

    private int max;

    private TimeUnit unit;

    @Override
    public void initialize(DateLimit constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
        this.unit = constraintAnnotation.unit();
    }

    @Override
    public boolean isValid(Date value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (min < 0 || max < 0) {
            return false;
        }
        //当前时间+偏移
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beforeDate = null;
        LocalDateTime afterDate = null;
        if (Objects.equals(unit, TimeUnit.SECONDS)) {
            beforeDate = now.minusSeconds(min);
            afterDate = now.plusSeconds(max);
        } else if (Objects.equals(unit, TimeUnit.MINUTES)) {
            beforeDate = now.minusMinutes(min);
            afterDate = now.plusMinutes(max);
        } else if (Objects.equals(unit, TimeUnit.HOURS)) {
            beforeDate = now.minusHours(min);
            afterDate = now.plusHours(max);
        } else if (Objects.equals(unit, TimeUnit.DAYS)) {
            beforeDate = now.minusDays(min);
            afterDate = now.plusDays(max);
        } else {
            return false;
        }

        //输入的时间
        LocalDateTime sourceDate = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault());

        if (min > 0 && max > 0) {
            if (beforeDate.isBefore(sourceDate) && afterDate.isAfter(sourceDate)) {
                return true;
            }
        } else if (min == 0 && max > 0) {
            if (afterDate.isAfter(sourceDate)) {
                return true;
            }
        } else if (min > 0 && max == 0) {
            if (beforeDate.isBefore(sourceDate)) {
                return true;
            }
        }

        return false;
    }
}
